#include <stdio.h>
#include <speak_lib.h> 
 
FILE *f_wave = NULL;
 
void Write4Bytes(FILE *f, int value)
{//=================================
// Write 4 bytes to a file, least significant first
	int ix;
 
	for(ix=0; ix<4; ix++)
	{
		fputc(value & 0xff,f);
		value = value >> 8;
	}
}
 
static int OpenWaveFile(const char *path, int rate)//rate 22050
//=================================================
{
	// Set the length of 0x7ffff000 for --stdout
	// This will be changed to the correct length for -w (write to file)
	static unsigned char wave_hdr[44] = {
		'R','I','F','F',0x24,0xf0,0xff,0x7f,'W','A','V','E','f','m','t',' ',
		0x10,0,0,0,1,0,1,0,  9,0x3d,0,0,0x12,0x7a,0,0,
		2,0,0x10,0,'d','a','t','a',  0x00,0xf0,0xff,0x7f};
 
	if(path == NULL)
		return(2);
 
	if(strcmp(path,"stdout")==0)
		f_wave = stdout;
	else
		f_wave = fopen(path,"wb");
 
	if(f_wave != NULL)
	{
		fwrite(wave_hdr,1,24,f_wave);
		Write4Bytes(f_wave,rate);
		Write4Bytes(f_wave,rate * 2);
		fwrite(&wave_hdr[32],1,12,f_wave);
		return(0);
	}
	return(1);
}   //  end of OpenWaveFile
 
 
static void CloseWaveFile()
//=========================
{
   unsigned int pos;
 
   if((f_wave == NULL) || (f_wave == stdout))
      return;
 
   fflush(f_wave);
   pos = ftell(f_wave);
 
	fseek(f_wave,4,SEEK_SET);
	Write4Bytes(f_wave,pos - 8);
 
	fseek(f_wave,40,SEEK_SET);
	Write4Bytes(f_wave,pos - 44);
 
 
   fclose(f_wave);
   f_wave = NULL;
 
} // end of CloseWaveFile
 
int SynthCallback(short *wav, int numsamples, espeak_EVENT *events)
{
    // 你可以根据源码程序里编写这部分代码实现生成语音文件功能
    int wavDataIndex = 0;
	if(wav == NULL)
		return 1;
	else{
		while(wav[wavDataIndex+numsamples] != NULL)
			wavDataIndex++;
		fwrite(wav,sizeof(short),numsamples,f_wave);
		return(0);
	}
}
 
void main() 
{
    // TODO: Add your control notification handler code here
    char word[] = "hello world!";
    //espeak_Initialize(AUDIO_OUTPUT_PLAYBACK, 0, NULL, 0);
    espeak_Initialize(AUDIO_OUTPUT_SYNCHRONOUS, 0, NULL, 0);
    //espeak_Initialize(AUDIO_OUTPUT_SYNCH_PLAYBACK, 0, NULL, 0);
    espeak_SetSynthCallback(SynthCallback);   // 设置回调函数
    espeak_SetVoiceByName("en");
	OpenWaveFile("test.wav",22050);
    espeak_Synth(word, 100, 0, POS_CHARACTER, 0, espeakCHARS_UTF8, NULL ,NULL);
    espeak_Synchronize();
    espeak_Terminate();
	CloseWaveFile();
}
